package com.luoy.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;

/**
 * 临时文件管理工具类
 *
 * @author luoyuan
 * @create 2018-06-28-下午3:36
 */
@Slf4j
public class FileUtil {
    /**
     * 上传文件 (修改文件名)
     *
     * @param multipartFile
     * @param key
     * @param filePath
     * @param fileNameStart
     * @return
     */
    public static String upload(MultipartFile multipartFile, String key, String filePath, String fileNameStart, String[] fileExtension) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件的后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //判断文件扩展名是否正确
        if (fileExtension != null) {
            if (!Arrays.asList(fileExtension).contains(suffixName)) {
                log.error("[上传文件] 文件扩展名不正确,multipartFile{},正确扩展名为:fileExtension:{}", suffixName, fileExtension);
                throw new RuntimeException("文件扩展名不正确");
            }
        }
        //生成文件名
        fileName = String.format(fileNameStart, key) + suffixName;
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 上传文件 (不修改文件名)
     *
     * @param multipartFile
     * @param filePath
     * @return
     */
    public static String upload(MultipartFile multipartFile, String filePath) {
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }

    /**
     * 删除文件
     *
     * @param filePathAndName String  文件路径及名称
     * @return boolean
     */
    public static void delFile(String filePathAndName) {
        try {
            File file = new File(filePathAndName);
            if (!file.exists() && !file.delete()) {
                log.error("[删除文件] 文件不存在,filePathAndName:{}", filePathAndName);
            }
            file.delete();
        } catch (SecurityException e) {
            log.error("[删除文件] 无权限删除,filePathAndName:{}", filePathAndName);
        }
    }

    /**
     * 移动文件到指定目录
     *
     * @param oldPath
     * @param newPath
     */
    public static void moveFile(String oldPath, String newPath) {
        try {
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {
                //文件存在时
                File newFile = new File(newPath);
                //监测是否存在目录
                if (!newFile.getParentFile().exists()) {
                    newFile.getParentFile().mkdirs();
                }
                oldfile.renameTo(newFile);
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载
     *
     * @param response
     * @param fileName
     * @param filePath
     */
    public static void download(HttpServletResponse response, String fileName, String filePath) {
        //流
        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            os = response.getOutputStream();
            bis = new BufferedInputStream(new FileInputStream(new File(filePath + fileName)));
            //设置响应头等信息
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentLength(bis.available());
            int i = bis.read(buff);
            //文件写到输出流中
            while (i != -1) {
                os.write(buff, 0, buff.length);
                os.flush();

                i = bis.read(buff);
            }
        } catch (FileNotFoundException e) {
            log.error("[文件下载] 文件不存在,filePath:{},fileName:{}", filePath, fileName);
            throw new RuntimeException("文件未找到");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                //关闭资源
                try {
                    os.close();
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}